package nps

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/beego/beego/v2/server/web"
	"github.com/kirinlabs/HttpRequest"
	"rate/common/consts"
	"rate/common/util/objectUtils"
	"rate/common/util/secret"
	"rate/pojo/entity"
	"strconv"
	"time"
)

var createClientUrl = "/client/add/" // 创建客户端

// 获取服务器地址
func getHost(area int) string {
	// 二级域名
	domain := ""
	// 端口
	port := ""
	if area == consts.HZ {
		domain = objectUtils.GetConfig("HZDomain")
		port = objectUtils.GetConfig("HZPort")
	} else if area == consts.BJ {
		domain = objectUtils.GetConfig("BJDomain")
		port = objectUtils.GetConfig("BJPort")
	} else {
		return ""
	}
	// 主域名
	mainDomain := objectUtils.GetConfig("mainDomain")
	// 协议
	tro := objectUtils.GetConfig("Tro")
	return fmt.Sprintf("%s%s.%s:%s", tro, domain, mainDomain, port)
}

// 获取api调用key
func getAuthKey() (int64, string) {
	timestamp := time.Now().Unix()
	key := web.AppConfig.DefaultString("AuthKey", "") + strconv.FormatInt(timestamp, 10)
	return timestamp, secret.Md5(key)
}

// nps 返回结果处理
func handlerResult(resp *HttpRequest.Response) map[string]interface{} {
	body, _ := resp.Body()
	result := make(map[string]interface{})
	if err := json.Unmarshal(body, &result); err != nil {
		logs.Error("NPS调用返回数据格式化失败，body:%s, err:%s", body, err)
	} else {
		logs.Info("NPS返回成功，%s", result)
	}
	return result
}

// CreateClientApi 创建客户端
func CreateClientApi(client entity.Client, area int) {
	timestamp, key := getAuthKey()
	data := map[string]interface{}{
		"auth_key":          key,
		"timestamp":         timestamp,
		"vkey":              client.Vkey,
		"config_conn_allow": client.ConfigConnAllow,
		"compress":          client.Compress,
		"crypt":             client.Crypt,
		"rate_limit":        1024,
		"max_conn":          1,
		"max_tunnel":        2,
	}
	_, err := HttpRequest.Post(getHost(area)+createClientUrl, data)
	logs.Info("NPS, CreateClient, params, %s", data)
	if err != nil {
		logs.Error(err.Error())
	}
}
